package com.sctu.httpvollry;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;

import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;

/**
 * 网络图片异步
 * 
 * @author Administrator
 *
 */
public class RequestManager {
	
	private RequestQueue mRequestQueue;
	private static  ImageLoader mImageLoader;
	private static RequestManager requestmanager = null;
	
	/**
	 * constant

	 * @param request
	 * @param activity
	 */
	public RequestManager(RequestQueue request,Activity activity){
		this.mRequestQueue = request;
		init(activity);
	}
	
	/**
	 * 单列
	 * 
	 * @param request
	 * @param activity
	 * @return
	 */
	public static RequestManager getInstance(RequestQueue request,Activity activity){
		if(requestmanager == null){
			requestmanager = new RequestManager(request,activity);
		}
		return requestmanager;
	}
	
	/**
	 * 初始化
	 * 
	 * @param context
	 */
	@TargetApi(Build.VERSION_CODES.ECLAIR)
	public void init(Context context) {
		int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
				.getMemoryClass();
		// Use 1/8th of the available memory for this memory cache.
		int cacheSize = 1024 * 1024 * memClass / 8;
        Log.i("cachesize",String.valueOf(cacheSize));
		mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
	}

	/**
	 * 获取异步队列
	 * 
	 * @return
	 */
	public RequestQueue getRequestQueue() {
		if (mRequestQueue != null) {
			return mRequestQueue;
		} else {
			throw new IllegalStateException("RequestQueue not initialized");
		}
	}
	
	/**
	 * 添加进异步队列
	 * 
	 * @param request
	 * @param tag
	 */
	public void addRequest(Request<?> request, Object tag) {
        if (tag != null) {
            request.setTag(tag);
        }
        mRequestQueue.add(request);
    }
	
	public void cancelAll(Object tag) {
        mRequestQueue.cancelAll(tag);
    }

	/**
	 * 返回单列的imageloader
	 * 
	 * @return
	 */
	public ImageLoader getImageLoader() {
		if (mImageLoader != null) {
			return mImageLoader;
		} else {
			throw new IllegalStateException("imageloader没有实例化");
		}
	}
}
